<?php

namespace App\Models;


class WaterBill extends BaseModel
{
    protected $table = "waterbill";

    protected $redisListTable = "bill_list";

    protected $redisKeyTable = "bill_list_keys";

    protected $rules = [
        'admin_id' => 'required',
        'shop_id' => 'required',
        'goods_id' => 'required',
        'goods_name' => 'required|between:1,20',
        'goods_price' => ['required', 'numeric', 'regex:/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/'],
        'shop_price' => 'numeric',
        'goods_num' => 'required|numeric',
        'category_id' => 'required|numeric',
        'brand_id' => 'required|numeric',
        'bucket_category_id' => 'required|numeric',
        'waterbill_category' => 'required',
    ];

    protected $message = [
        'admin_id.required' => '用户ID获取失败',
        'shop_id.required' => '店铺ID获取失败',
        'goods_id.required' => '商品ID获取失败',
        'goods_name.required' => '商品名称必须填写',
        'goods_name.between' => '商品名称不能超过20个字',
        'goods_price.required' => '商品价格必须填写',
        'goods_price.numeric' => '商品价格必须是纯数字',
        'goods_price.regex' => '商品价格不能小于0',
        'shop_price.numeric' => '市场价格必须是纯数字',
        'goods_num.required' => '商品库存必须填写',
        'goods_num.numeric' => '商品库存必须是纯数字',
//        'goods_num.min' => '商品库存不能小于1',
        'goods_category_id.required' => '请选择商品所属分类',
        'category_id.numeric' => '非法分类数据',
        'brand_id.required' => '请选择商品所属品牌',
        'brand_id.numeric' => '非法品牌数据',
        'bucket_category_id.required' => '请选择商品所属水桶分类',
        'bucket_category_id.numeric' => '非法水桶分类数据',
        'waterbill_category.required' => '请选择水票套餐',
    ];

    protected $casts = [
        'waterbill_category' => 'array'
    ];

    public function getGoodsList()
    {
        $keyword = request('keyword');
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where);
        $txtStr['status'] = [1 => '上架', -1 => '下架', 0 => '待审核'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getOwnGoodsList()
    {
        $keyword = request('keyword');
        $where['admin_id'] = plat_admin_id();
        $where['status'] = ['>=', 0];
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where);
        $txtStr['status'] = [1 => '上架', -1 => '下架', 0 => '待审核'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getGoodsListByShopId($shopId, $fields = '')
    {
        $keyword = request('keyword');
        $where['shop_id'] = $shopId;
        $where['status'] = ['>', 0];
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        !$fields && $fields = 'id,goods_id,goods_name,goods_num,goods_price,waterbill_category';
        $rows = $this->_getPageList($where, $fields);
        return $rows;
    }

    public function addFromStore()
    {
        $shopId = request('shop_id');
        $ids = request('ids');
        if (!(!empty($ids) && is_array($ids))) {
            $this->error = '请选择要操作的数据';
            return false;
        }
        $where['id'] = ['in', $ids];
        $where['admin_id'] = plat_admin_id();
        $goods = new Goods();
        $goodsList = $goods->_getList($where)->toArray();
        if (empty($goodsList)) {
            $this->error = '商品数据不存在';
            return false;
        }
        if (!$shopId) {
            $this->error = '非法操作';
            return false;
        }
        if (request('old')) {
            $old = explode(',', request('old'));
            $arr = array_diff($old, $ids);
            if (!empty($arr)) {
                foreach ($arr as $v) {
                    if (in_array($v, $old)) {
                        $_res = $this->checkData($arr);
                        if (!$_res) {
                            $this->error = '商品正在出售中无法删除';
                            return false;
                        }
                    }
                }
            }
            $ids = array_diff($ids, $old);
        }
        if (empty($ids)) {
            return true;
        }
        $data = [];
        foreach ($ids as $k => $v) {
            foreach ($goodsList as $n) {
                if ($n['id'] == $v) {
                    $data[] = $n;
                }
            }
        }
        if (empty($data)) {
            $this->error = '无效商品数据';
            return false;
        }
        foreach ($data as $k => $v) {
            $data[$k]['shop_id'] = $shopId;
            $data[$k]['goods_id'] = $v['id'];
            $data[$k]['addtime'] = time();
            $data[$k]['created_at'] = date('Y-m-d H:i:s');
            $data[$k]['updated_at'] = date('Y-m-d H:i:s');
            unset($data[$k]['id']);
        }
        foreach ($data as $v) {
            if (!$this->_validate($v)) {
                return false;
            }
        }
        $res = $this->_add($data);
        if (!$res) {
            $this->error = '添加失败，请稍后再试';
            return false;
        }
        $shop = new Shop();
        $shop->_update(['id' => $shopId], ['total_goods_num' => count($ids)]);
        return $res;
    }

    public function checkData($ids)
    {
        if (!$ids) {
            $this->error = '参数错误';
            return false;
        }

        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['goods_id'] = ['in', $ids];
        $where['shop_id'] = request('shop_id');
        $res = $this->_getList($where);
        if ($res) {
            return false;
        }
        return true;
    }

    public function addOrUpdate()
    {
        $ids = request('ids');
        if (!(!empty($ids) && is_array($ids))) {
            $this->error = '请选择水票套餐';
            return false;
        }

        $shopGoods = new ShopGoods();
        $goods = $shopGoods->_getOneById(request('id'));
        if (!$goods) {
            $this->error = '该商品信息不存在';
            return false;
        }
        $data = $goods->toArray();
        $data['shop_goods_id'] = $data['id'];
        unset($data['id']);
        unset($data['created_at']);
        unset($data['updated_at']);
        $where['id'] = ['in', $ids];
        $shopWaterBillCategory = new ShopWaterBillCategory();
        $category = $shopWaterBillCategory->_getOne(['shop_id' => request('shop_id')], 'category_data');
        if (!$category) {
            $this->error = '请先添加水票套餐，才能添加水票';
            return false;
        }
        $arr = [];
        foreach ($category['category_data'] as $k => $v) {
            if (in_array($v['id'], $ids)) {
                $arr[] = $v;
            }
        }
        $data['waterbill_category'] = $arr;
        $data['goods_price'] = floatval(trim(request('goods_price', 1)));
        $data['shop_price'] = floatval(trim(request('shop_price')));
        $data['status'] = request('status', 1);
        $data['addtime'] = time();
//        $this->rules['goods_id'] .= ',' . $data['shop_id']; //唯一字段验证,在更新时排除当前店铺中的当前商品id
        if (!$this->_validate($data)) {
            return false;
        }
        $condition['goods_id'] = $data['goods_id'];
        $condition['shop_id'] = $data['shop_id'];
        $condition['status'] = 1;
        $res = $this->_getOne($condition);
        if ($res) {
            $this->error = '该商品水票信息已经存在，请勿重复添加！';
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存水票信息失败！';
            return false;
        }
        $this->_redisGenerateBillListBySid($data['shop_id']);
        return $res;
    }


    public function edit()
    {
        $id = request('id');
        if (!$id) {
            $this->error = '该水票信息不存在';
            return false;
        }
        $ids = request('ids');
        if (!(!empty($ids) && is_array($ids))) {
            $this->error = '请选择水票套餐';
            return false;
        }
        $where['id'] = ['in', $ids];
        $shopWaterBillCategory = new ShopWaterBillCategory();
        $category = $shopWaterBillCategory->_getOne(['shop_id' => request('shop_id')], 'category_data');
        if (!$category) {
            $this->error = '请先添加水票套餐，才能添加水票';
            return false;
        }
        $arr = [];
        foreach ($category['category_data'] as $k => $v) {
            if (in_array($v['id'], $ids)) {
                $arr[] = $v;
            }
        }
        $data = $this->_getOneById($id)->toArray();
        $data['waterbill_category'] = $arr;
        $data['goods_price'] = floatval(trim(request('goods_price', 1)));
        $data['shop_price'] = floatval(trim(request('shop_price')));
        if (!$this->_validate($data)) {
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '编辑水票信息失败！';
            return false;
        }
        $this->_redisGenerateBillListBySid(request('shop_id'));
        return $res;
    }

    public function _redisGetBillListByShopId($shopId)
    {
        if (!$shopId) {
            $this->error = '非法操作';
            return false;
        }
        $page = request('page', 1);
        $table = $this->redisListTable;
        $key = 'shopid:' . $shopId . ':page:' . $page;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            return unserialize($res[0]);
        }
        $this->_redisSetBillListKeysBySid($shopId, $key);
        $where['shop_id'] = $shopId;
        $where['status'] = ['>', 0];
        $order['sort'] = 'asc';
        $rows = $this->_getPageList($where, 'id,goods_id,goods_name,goods_num,goods_price,waterbill_category', $order);
        $this->redis->hmset($table, [$key => serialize($rows)]);
        return $rows;
    }

    public function _redisGetBillListByKeys($keys)
    {
        if (empty($keys)) {
            $this->error = '非法操作';
            return false;
        }
        $table = $this->redisListTable;
        $rows = [];
        foreach ($keys as $v) {
            if ($this->redis->hexists($table, $v)) {
                $res = $this->redis->hmget($table, $v);
                $rows[] = unserialize($res[0])['data'];
            }
        }
        $arr = [];
        if (!empty($rows)) {
            foreach ($rows as $v) {
                if (is_array($v)) {
                    foreach ($v as $m) {
                        $arr[] = $m;
                    }
                }
            }
        }
        return $arr;
    }

    public function _redisDelBillListByKey($key)
    {
        if (!$key) {
            $this->error = '非法操作';
            return false;
        }
        $table = $this->redisListTable;
        $this->redis->hdel($table, $key);
    }

    public function _redisSetBillListKeysBySid($sid, $value)
    {
        if (!$value && !$sid) {
            $this->error = '非法操作';
            return false;
        }
        $table = $this->redisKeyTable;
        $key = $sid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                $keyArr = unserialize($res[0]);
                if (in_array($value, $keyArr)) {
                    return false;
                }
                $keyArr[] = $value;
                return $this->redis->hmset($table, [$key => serialize($keyArr)]);
            }
        }
        $this->redis->hmset($table, [$key => serialize([$value])]);
    }

    public function _redisGetBillListKeysBySid($sid)
    {
        if (!$sid) {
            $this->error = '非法操作';
            return false;
        }
        $table = $this->redisKeyTable;
        $key = $sid;
        $res = $this->redis->hmget($table, $key);
        if ($res) {
            return unserialize($res[0]);
        }
        return false;
    }

    public function _redisGenerateBillListBySid($sid)
    {
        if (!$sid) {
            $this->error = '非法操作';
            return false;
        }
        $keys = $this->_redisGetBillListKeysBySid($sid);
        if ($keys && is_array($keys)) {
            foreach ($keys as $v) {
                $this->_redisDelBillListByKey($v);
            }
        }
    }

    public function _redisGenerateBillListByAid($aid)
    {
        $shop = new Shop();
        $res = $shop->_getList(['admin_id' => $aid], 'id')->toArray();
        if ($res) {
            foreach ($res as $v) {
                $keys = $this->_redisGetBillListKeysBySid($v['id']);
                if ($keys && is_array($keys)) {
                    foreach ($keys as $v) {
                        $this->_redisDelBillListByKey($v);
                    }
                }
            }
        }

    }


}
